//
//  LiaisonDetailViewController.m
//  FMS
//
//  Created by Steven on 10/14/13.
//  Copyright (c) 2013 QGSVN. All rights reserved.
//

#import "LiaisonDetailViewController.h"
#import <QuartzCore/QuartzCore.h>
#import "LiaisonBaseLite.h"

@interface LiaisonDetailViewController ()

@end

@implementation LiaisonDetailViewController
@synthesize dictLiaison;
@synthesize delegate;
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil statusView:(int)status
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        dictLanguage = [ApplicationDelegate.arrayLanguage objectAtIndex:0];
        statusView = status;
        
        [self addTopBar];
        if (self.navBar) {
            self.navBar.navBarViewDelegate = self;
            
            if (statusView == DETAIL_VIEW)
                [self.navBar.rightButton setBackgroundImage:[UIImage imageNamed:@"btnEdit.png"] forState:UIControlStateNormal];
            else
                [self.navBar.rightButton setBackgroundImage:[UIImage imageNamed:@"btnSaveView.png"] forState:UIControlStateNormal];
            switch (statusView) {
                case ADD_VIEW:
                    self.navBar.titleLabel.text = [dictLanguage objectForKey:@"liaison.title-add-new-liaison"];
                    break;
                    
                case EDIT_VIEW:
                    self.navBar.titleLabel.text = [dictLanguage objectForKey:@"liaison.title-edit"];
                    break;
                    
                case DETAIL_VIEW:
                    self.navBar.titleLabel.text = [dictLanguage objectForKey:@"liaison.title-detail"];
                    break;
                    
                default:
                    break;
            }
        }
        
    }
    return self;
}

- (void)reloadLiaison{
    if ([[dictLiaison objectForKey:@"Table"] isEqualToString:kUserDocType]) {
        [btnTypeLiaison setTitle:[dictLiaison objectForKey:@"role"] forState:UIControlStateNormal];
        tfCompany.text = [dictLiaison objectForKey:@"company"];
        tfPersonInCharge.text = [dictLiaison objectForKey:@"email"];
        tfEmail.text = [dictLiaison objectForKey:@"email"];
        tfContact.text = [dictLiaison objectForKey:@"phone"];
        tfAddress.text = [dictLiaison objectForKey:@"address"];
        self.navBar.rightButton.hidden = YES;
    }
    else{
        [btnTypeLiaison setTitle:[dictLiaison objectForKey:@"typeLiaison"] forState:UIControlStateNormal];
        tfCompany.text = [dictLiaison objectForKey:@"company"];
        tfPersonInCharge.text = [dictLiaison objectForKey:@"personInCharge"];
        tfEmail.text = [dictLiaison objectForKey:@"email"];
        tfContact.text = [dictLiaison objectForKey:@"contactNumber"];
        tfAddress.text = [dictLiaison objectForKey:@"address"];
    }
    
    [self.tbLiaison reloadData];
}
- (void)selectTypeLiaison:(id)sender{
    
    UIButton *btnSender = (UIButton *)sender;
    
    FilterViewController *controller = [[FilterViewController alloc] initWithStyle:UITableViewStylePlain filterType:filter_liaison];
    controller.delegate = self;
    popoverController = [[UIPopoverController alloc] initWithContentViewController:controller];
    
    [popoverController presentPopoverFromRect:btnSender.frame inView:btnSender.superview permittedArrowDirections:UIPopoverArrowDirectionAny animated:YES];
}
- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    btnTypeLiaison = [[CustomButton alloc] initWithFrame:CGRectMake(495, 10, 350, 30)];
    [btnTypeLiaison addTarget:self action:@selector(selectTypeLiaison:) forControlEvents:UIControlEventTouchUpInside];
    if (statusView == DETAIL_VIEW)
        [btnTypeLiaison converToLabel];
    else
        [btnTypeLiaison converCombobox];
    
    lblCompany = [[UILabel alloc] initWithFrame:CGRectMake(495, 10, 350, 30)];
    lblPersonInCharge = [[UILabel alloc] initWithFrame:CGRectMake(495, 10, 350, 30)];
    lblEmail = [[UILabel alloc] initWithFrame:CGRectMake(495, 10, 350, 30)];
    lblContact = [[UILabel alloc] initWithFrame:CGRectMake(495, 10, 350, 30)];
    lblAddress = [[UILabel alloc] initWithFrame:CGRectMake(495, 10, 350, 30)];
    
    tfCompany = [[UITextField alloc] initWithFrame:CGRectMake(515, 10, 330, 30)];
    tfCompany.delegate = self;
    tfPersonInCharge = [[UITextField alloc] initWithFrame:CGRectMake(515, 10, 330, 30)];
    tfEmail = [[UITextField alloc] initWithFrame:CGRectMake(515, 10, 330, 30)];
    tfEmail.delegate = self;
    tfContact = [[UITextField alloc] initWithFrame:CGRectMake(515, 10, 330, 30)];
    tfContact.delegate = self;
    
    tfAddress = [[UITextField alloc] initWithFrame:CGRectMake(515, 10, 330, 30)];
    
    tfAddress.delegate = self;
    tfCompany.autocorrectionType = UITextAutocorrectionTypeNo;
    tfPersonInCharge.autocorrectionType = UITextAutocorrectionTypeNo;
    tfEmail.autocorrectionType = UITextAutocorrectionTypeNo;
    tfContact.autocorrectionType = UITextAutocorrectionTypeNo;
    tfAddress.autocorrectionType = UITextAutocorrectionTypeNo;
    
    tfEmail.keyboardType = UIKeyboardTypeEmailAddress;
    tfContact.keyboardType = UIKeyboardTypeNamePhonePad;
    
    tfAddress.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
    tfCompany.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
    tfPersonInCharge.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
    tfEmail.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
    tfContact.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
    
    tfCompany.font = [UIFont fontWithName:FMS_REGULAR_FONT size:15];
    tfCompany.textColor = FMS_COLOR_DEFAUL;
    
    tfPersonInCharge.font = [UIFont fontWithName:FMS_REGULAR_FONT size:15];
    tfPersonInCharge.textColor = FMS_COLOR_DEFAUL;
    
    tfEmail.font = [UIFont fontWithName:FMS_REGULAR_FONT size:15];
    tfEmail.textColor = FMS_COLOR_DEFAUL;
    
    tfContact.font = [UIFont fontWithName:FMS_REGULAR_FONT size:15];
    tfContact.textColor = FMS_COLOR_DEFAUL;
    
    tfAddress.font = [UIFont fontWithName:FMS_REGULAR_FONT size:15];
    tfAddress.textColor = FMS_COLOR_DEFAUL;
    
    lblCompany.layer.borderColor = [[UIColor lightGrayColor] CGColor];
    lblPersonInCharge.layer.borderColor = [[UIColor lightGrayColor] CGColor];
    lblEmail.layer.borderColor = [[UIColor lightGrayColor] CGColor];
    lblContact.layer.borderColor = [[UIColor lightGrayColor] CGColor];
    lblAddress.layer.borderColor = [[UIColor lightGrayColor] CGColor];

    if (statusView == DETAIL_VIEW) {
        lblCompany.layer.borderWidth = 0;
        lblPersonInCharge.layer.borderWidth = 0;
        lblEmail.layer.borderWidth = 0;
        lblContact.layer.borderWidth = 0;
        lblAddress.layer.borderWidth = 0;
        
        tfPersonInCharge.userInteractionEnabled = NO;
        tfEmail.userInteractionEnabled = NO;
        tfContact.userInteractionEnabled = NO;
        tfAddress.userInteractionEnabled = NO;
        tfCompany.userInteractionEnabled = NO;
    }
    else{
        lblCompany.layer.borderWidth = 1;
        lblPersonInCharge.layer.borderWidth = 1;
        lblEmail.layer.borderWidth = 1;
        lblContact.layer.borderWidth = 1;
        lblAddress.layer.borderWidth = 1;
    }
    if (statusView == ADD_VIEW) {
        [btnTypeLiaison setTitle:[dictLanguage objectForKey:@"liaison.title-select-type"] forState:UIControlStateNormal];
    }
}

- (void)didReceiveMemoryWarning
{
    dictLiaison = nil;
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - NavViewDelegate

- (void)didClickedLeftButton {
    if (statusView == EDIT_VIEW) {
        statusView = DETAIL_VIEW;
        lblCompany.layer.borderWidth = 0;
        lblPersonInCharge.layer.borderWidth = 0;
        lblEmail.layer.borderWidth = 0;
        lblContact.layer.borderWidth = 0;
        lblAddress.layer.borderWidth = 0;
        [btnTypeLiaison converToLabel];
        
        tfCompany.userInteractionEnabled = NO;
        tfPersonInCharge.userInteractionEnabled = NO;
        tfEmail.userInteractionEnabled = NO;
        tfContact.userInteractionEnabled = NO;
        tfAddress.userInteractionEnabled = NO;
        
        self.navBar.titleLabel.text = [dictLanguage objectForKey:@"liaison.title-detail"];
        [self.navBar.rightButton setBackgroundImage:[UIImage imageNamed:@"btnEdit.png"] forState:UIControlStateNormal];
    }
    else
        [self.navigationController popViewControllerAnimated:YES];
}
- (void)saveLiaisonInfo{
    if (statusView == EDIT_VIEW) {
        if (![[btnTypeLiaison titleForState:UIControlStateNormal] isEqual:[dictLanguage objectForKey:@"liaison.title-select-type"]]) {
            if (contactType) {
                [dictLiaison setObject:[contactType objectForKey:@"filterName"] forKey:@"typeLiaison"];
                [dictLiaison setObject:[contactType objectForKey:@"index"] forKey:@"typeLiaisonId"];
            }
        }
        [dictLiaison setObject:tfCompany.text forKey:@"company"];
        [dictLiaison setObject:tfPersonInCharge.text forKey:@"personInCharge"];
        [dictLiaison setObject:tfEmail.text forKey:@"email"];
        [dictLiaison setObject:tfContact.text forKey:@"contactNumber"];
        [dictLiaison setObject:tfAddress.text forKey:@"address"];

    }
    else{
        //test
        [btnTypeLiaison setTitle:@"MA" forState:UIControlStateNormal];
        dictLiaison = [NSMutableDictionary dictionaryWithObjectsAndKeys:kLiaisonDocType,@"Table",[contactType objectForKey:@"filterName"],@"typeLiaison",[contactType objectForKey:@"index"],@"typeLiaisonId",tfCompany.text,@"company",tfPersonInCharge.text,@"personInCharge",tfEmail.text,@"email",tfContact.text,@"contactNumber",tfAddress.text,@"address",@"-1",@"indexRow", nil];
        
    }
    NSString *messageFailed = nil;
    int row = [[dictLiaison objectForKey:@"indexRow"] intValue];
    
    [dictLiaison removeObjectForKey:@"indexRow"];
    
    if (statusView == ADD_VIEW)
    {
        if ([LiaisonBaseLite getLiaisonByEmail:tfEmail.text] != nil) {
            messageFailed = [dictLanguage objectForKey:@"liaison.liaison-error-exist-email-address"];
        }
        else{
            [dictLiaison setObject:[[NSUserDefaults standardUserDefaults] objectForKey:ACCOUNT_ID] forKey:@"userId"];
            [dictLiaison setObject:[NSNumber numberWithInt:1] forKey:@"status"];
            
            NSString *contactId = [LiaisonBaseLite generationContactId];
            [dictLiaison setObject:contactId forKey:@"contactId"];
            
            NSError *error;
            [[CouchBaseLiteLib sharedCouchBaseLite] createDocument:dictLiaison error:&error];
            if (error) {
                messageFailed = [dictLanguage objectForKey:@"liaison.liaison-failed-add"];
            }
        }
        
    }
    else{
        NSError *error;
        [[CouchBaseLiteLib sharedCouchBaseLite] updateDocument:dictLiaison error:&error];
        if (error)
            messageFailed = [dictLanguage objectForKey:@"liaison.liaison-failed-update"];
    }
    if (messageFailed) {
        UIAlertView *dialog;
        dialog = [[UIAlertView alloc] initWithTitle:[dictLanguage objectForKey:@"general.warning"] message:messageFailed delegate:nil cancelButtonTitle:[dictLanguage objectForKey:@"general.ok"] otherButtonTitles:nil];
        [dialog show];
    }
    else{
        
        [dictLiaison setObject:[NSNumber numberWithInt:row] forKey:@"indexRow"];
        
        if ([delegate respondsToSelector:@selector(didUpdateLiaisonInfo:)]) {
            [delegate didUpdateLiaisonInfo:dictLiaison];
        }
        NSString *message;
        if (statusView == ADD_VIEW)
            message = [dictLanguage objectForKey:@"liaison.liaison-add-success"];
        else
            message = [dictLanguage objectForKey:@"liaison.liaison-update-success"];
        UIAlertView *dialog = [[UIAlertView alloc] initWithTitle:nil message:message delegate:nil cancelButtonTitle:[dictLanguage objectForKey:@"general.ok"] otherButtonTitles:nil];
        [dialog show];
        [self.navigationController popViewControllerAnimated:YES];
    }
}

- (void)didClickedRightButton{
    if (statusView == DETAIL_VIEW) {
        NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
        NSMutableDictionary *permissionDict = [userDefaults objectForKey:LIAISON_PERMISSION];
        BOOL isEditable = [[permissionDict objectForKey:@"update"] boolValue];
        if (!isEditable) {
            UIAlertView *dialog = [[UIAlertView alloc] initWithTitle:[dictLanguage objectForKey:@"general.warning"] message:[dictLanguage objectForKey:@"general.permission.no-right-access"] delegate:nil cancelButtonTitle:[dictLanguage objectForKey:@"general.ok"] otherButtonTitles:nil];
            [dialog show];
            return;
        }
        
        statusView = EDIT_VIEW;
        
        lblCompany.layer.borderWidth = 1;
        lblPersonInCharge.layer.borderWidth = 1;
        lblEmail.layer.borderWidth = 1;
        lblContact.layer.borderWidth = 1;
        lblAddress.layer.borderWidth = 1;
        
        [btnTypeLiaison returnDefaultCustom];
        [btnTypeLiaison converCombobox];
        
        tfCompany.userInteractionEnabled = YES;
        tfPersonInCharge.userInteractionEnabled = YES;
        tfEmail.userInteractionEnabled = YES;
        tfContact.userInteractionEnabled = YES;
        tfAddress.userInteractionEnabled = YES;
        
        self.navBar.titleLabel.text = [dictLanguage objectForKey:@"liaison.title-edit"];

        [self.navBar.rightButton setBackgroundImage:[UIImage imageNamed:@"btnSaveView.png"] forState:UIControlStateNormal];
    }
    else{
        
        NSString *messgeError = nil;
//        if ([[btnTypeLiaison titleColorForState:UIControlStateNormal] isEqual:[dictLanguage objectForKey:@"liaison.title-select-type"]]) {
//            
//        }
        NSString *emailRegexString	= @"^[_A-Za-z0-9-]+(\\.[_A-Za-z0-9-]+)*@[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$";
        if ([[btnTypeLiaison titleForState:UIControlStateNormal] isEqualToString:[dictLanguage objectForKey:@"liaison.title-select-type"]]) {
            messgeError = [dictLanguage objectForKey:@"liaison.title-required-select-contact-type"];
        }
        else if (tfEmail.text == nil || [tfEmail.text isEqualToString:@""]) {
            messgeError = [dictLanguage objectForKey:@"liaison.title-required-email"];
        }
        else if (![tfEmail.text isMatchedByRegex:emailRegexString]) {
            messgeError = [dictLanguage objectForKey:@"liaison.title-invalid-email"];
        }
        else if (tfCompany.text == nil || [tfCompany.text isEqualToString:@""]) {
            messgeError = [dictLanguage objectForKey:@"liaison.title-required-company"];
        }
        else if (tfPersonInCharge.text == nil || [tfPersonInCharge.text isEqualToString:@""]) {
            messgeError = [dictLanguage objectForKey:@"liaison.title-required-person-in-charge"];
        }
        else if (tfContact.text == nil || [tfContact.text isEqualToString:@""]) {
            messgeError = [dictLanguage objectForKey:@"liaison.title-required-contact"];
        }
        else if (tfAddress.text == nil || [tfAddress.text isEqualToString:@""]) {
            messgeError = [dictLanguage objectForKey:@"liaison.title-required-address"];
        }
        if (messgeError == nil)
            [self saveLiaisonInfo];
        else
            [self showErrorMessage:messgeError];
    }
}
#pragma mark - filterview delegate
- (void)didSelectFilter:(NSMutableDictionary *)filterDict{
    [self didmissPopoverController];
    [btnTypeLiaison setTitle:[filterDict objectForKey:@"filterName"] forState:UIControlStateNormal];
    contactType = filterDict;
}
#pragma mark - Text Field Delegate

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
    int newLength = [[textField.text stringByReplacingCharactersInRange:range withString:string] length];
    if ((newLength >= 50 && textField == tfContact) || (newLength >= 75 &&( textField == tfAddress||textField == tfCompany || textField == tfPersonInCharge || textField == tfEmail)))
        return NO;
    return YES;
}
#pragma mark - Table view data source
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 50;
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 6;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";
    UITableViewCell *cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    UILabel *lblTitle = [[UILabel alloc] initWithFrame:CGRectMake(172, 14, 300, 22)];
    lblTitle.backgroundColor = [UIColor clearColor];
    lblTitle.textColor = [UIColor darkGrayColor];
    lblTitle.font = [UIFont fontWithName:FMS_REGULAR_FONT size:15];
    switch (indexPath.row) {
        case 0:
        {
            lblTitle.text = [dictLanguage objectForKey:@"liaison.title-contact-type-required"];
            
            [cell.contentView addSubview:btnTypeLiaison];
        }
            break;
        case 1:
        {
            lblTitle.text = [dictLanguage objectForKey:@"liaison.title-email-required"];
            [cell.contentView addSubview:lblEmail];
            [cell.contentView addSubview:tfEmail];
        }
            break;
        case 2:
        {
            lblTitle.text = [dictLanguage objectForKey:@"liaison.title-company-required"];
            [cell.contentView addSubview:lblCompany];
            [cell.contentView addSubview:tfCompany];
        }
            break;
        case 3:
        {
            lblTitle.text = [dictLanguage objectForKey:@"liaison.title-person-in-charge-required"];
            [cell.contentView addSubview:lblPersonInCharge];
            [cell.contentView addSubview:tfPersonInCharge];
            
        }
            break;
        case 4:
        {
            lblTitle.text = [dictLanguage objectForKey:@"liaison.title-contact-number-required"];
            [cell.contentView addSubview:lblContact];
            [cell.contentView addSubview:tfContact];
        }
            break;
        case 5:
        {
            lblTitle.text = [dictLanguage objectForKey:@"liaison.title-address-required"];
            [cell.contentView addSubview:lblAddress];
            [cell.contentView addSubview:tfAddress];
        }
            break;
        default:
            break;
    }
    [cell.contentView addSubview:lblTitle];
    // Configure the cell...
    
    return cell;
}

@end
